package com.cynteka.cyfoman.ui.collection;

import com.cynteka.cyfoman.core.collection.scxml.SCXMLCommand;
import com.cynteka.cyfoman.ui.AbstractChainAction;
import com.cynteka.cyfoman.ui.collection.factory.GridCollectionFactory;
import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;

import javax.swing.*;
import java.util.List;

/**
 * User: Sergey
 * Date: 09.08.11
 * Time: 15:40
 */
public class TriggerEventAction extends AbstractChainAction implements Command {

    private String collectionId;
    private List selected;

    public TriggerEventAction() {
    }

    public TriggerEventAction(String name) {
        super(name);
    }

    public TriggerEventAction(String name, Icon icon) {
        super(name, icon);
    }

    public TriggerEventAction(String name, Icon icon, String shortDescription) {
        super(name, icon);
        putValue(SHORT_DESCRIPTION, shortDescription);

    }

    public String getTriggerEvent() {
        return triggerEvent;
    }

    public void setTriggerEvent(String triggerEvent) {
        this.triggerEvent = triggerEvent;
    }

    private String triggerEvent;

    public String getCollectionId() {
        return collectionId;
    }

    public void setCollectionId(String collectionId) {
        this.collectionId = collectionId;
    }

    @Override
    protected Context createContext() {
        Context res = super.createContext();

        if(selected != null && !selected.isEmpty()) {
            res.put(SCXMLCommand.COLLECTION_ID_PARAM, collectionId);
            res.put(SCXMLCommand.TRIGGER_EVENT_PARAM, triggerEvent);
            Object o = selected.get(0);
            res.put(SCXMLCommand.OBJECT_PARAM, o);
        }
        return res;
    }
//
//    @Override
//    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
//        super.setBeanFactory(beanFactory);
//        Catalog catalog = (Catalog) beanFactory.getBean(Catalog.CATALOG_KEY);
//        catalog.addCommand(GridCollectionFactory.SELECTION_CHANGED_CMD, this);
//    }

    @Override
    public boolean execute(Context context) throws Exception {
        String curCollectionId = (String) context.get(GridCollectionFactory.COLLECTION_ID_PARAM);
        if(collectionId.equals(curCollectionId)) {
            selected = (List)context.get(GridCollectionFactory.SELECTED_OBJECTS_PARAM);
        } else {
            selected = null;
        }
        setEnabled(selected != null && !selected.isEmpty());

        return false;
    }
}
